package com.gen.common.interceptor;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.gen.common.constant.ATTConstants;
import com.gen.web.BaseController;


public class SpringLoginInterceptor extends HandlerInterceptorAdapter {
	private static final Logger log = LoggerFactory.getLogger(BaseController.class);
	private String mappingURL =".*/.*\\.do" ;
	
	@SuppressWarnings("unused")
	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) {
		String className = handler.getClass().getName();// packageName.ClassName
		String url= req.getRequestURL().toString();    
	    HttpSession session = req.getSession();
	    try {
		    if(url.matches(mappingURL)){
		    	
		    	if(session.getAttribute(ATTConstants.ADMIN_SESSION_KEY) == null){
		    		
		    		if(req.getHeader("x-requested-with")!=null && req.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){ 
			    		resp.setHeader("sessionstatus","timeout"); 
	    			} 
		    		req.getRequestDispatcher("/index.jsp").forward(req, resp);
					return false;
			    }
		    }
	    } catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
	    return true;
	}
}

